package com.lagou.module01.filter;

import com.lagou.module01.bean.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author: xyk
 * @Date: Create in 23:54 2021/3/27
 * @Description: 用户登录过滤
 */
@WebFilter(filterName = "LoginFilter", urlPatterns = {"/studentManage.jsp", "/mainPage.jsp"})
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        // 1.实现对用户访问主页面的过滤操作，也就是只有用户登录后才能访问主页面，否则一律拦截
        // 判断session中是否已有用户名信息，若没有则判断Cookie中是否有，若有放行，否则拦截
        HttpServletRequest httpServletRequest = (HttpServletRequest)req;
        HttpSession session = httpServletRequest.getSession();
        User user = (User) session.getAttribute("user");
        Cookie[] cookies = ((HttpServletRequest) req).getCookies();
        // 获取Servlet的请求路径
        String servletPath = httpServletRequest.getServletPath();
        String userName = null;
        // 判断session中是否已有用户信息
        if (null != user && servletPath.contains("mainPage")){
            chain.doFilter(req, resp);
        }else {
            // 判断cookie中是否有用户名信息
            for (Cookie cookie: cookies){
                String name = cookie.getName();
                if ("userName".equals(name)){
                    userName = name;
                    break;
                }
            }
            // 判断cookie中用户名信息是否为null
            if (null != userName){
                chain.doFilter(req, resp);
            }else {
                req.getRequestDispatcher("login.jsp").forward(req, resp);
            }
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
